<template>
    <el-row class="main">
        <el-col class="padd20 posa">
            <el-col class="box ">
                <div class="btn tab">
                    <el-input placeholder="搜索" style="margin: 0 5px;" v-model="searchtext">
                        <i slot="suffix" class="el-input__icon el-icon-search cp" @click.stop="listSchoolStu()"></i>
                    </el-input>
                    <el-button class="reset-comfirm-btn" @click="handleAdd()" style="margin-right: 7px;">+添加
                    </el-button>

                    <el-button class="reset-comfirm-btn" @click="handleExport">excel导入</el-button>
                    <el-link :href="stumburl" type="primary" style="width: 150px;">下载模板
                    </el-link>
                </div>
            </el-col>

            <el-col class="mt20 tab">
                <el-table :data="stupage.list" height="579" stripe
                    :header-cell-style="{ background: '#F0F1F8', color: '#2F3142' }" border v-loading="loading"
                    element-loading-text="加载中..." element-loading-spinner="el-icon-loading"
                    element-loading-background="rgba(0, 0, 0, 0.1)">
                    <el-table-column label="序号" width="80px" fixed align="center">
                        <template slot-scope="scope">
                            {{ (stupage.pageNum - 1) * stupage.pageSize + scope.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="姓名" width="100" align="center"></el-table-column>
                    <el-table-column prop="grade" label="年级" min-width="100" align="center"></el-table-column>
                    <el-table-column prop="zy" label="专业" min-width="100" align="center"></el-table-column>
                    <el-table-column prop="bj" label="班级" min-width="100" align="center"></el-table-column>
                    <el-table-column prop="xh" label="学号" min-width="100" align="center"></el-table-column>
                    <!-- <el-table-column prop="sfzh" label="身份证号" min-width="160" align="center"></el-table-column> -->
                    <el-table-column prop="acc" label="账号" min-width="100" align="center"></el-table-column>
                    <el-table-column prop="mobile" label="手机号" min-width="110" align="center"></el-table-column>
                    <el-table-column label="操作" align="center" width="200" fixed="right">
                        <template slot-scope="scope">
                            <el-col class="box box-pack-center box-align-center">
                                <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                                <el-button v-if="maxrole == 'admin'" size="mini" type="danger"
                                    @click="handleDelete(scope.row)">删除</el-button>
                                <el-button size="mini" type="primary" @click="handleResetPassword(scope.row)">重置密码
                                </el-button>
                            </el-col>
                        </template>
                    </el-table-column>
                </el-table>
                <el-col class="mt20">
                    <el-pagination @current-change="listSchoolStu" background layout="prev, pager, next"
                        :total="stupage.total" :current-page="stupage.pageNum" hide-on-single-page></el-pagination>
                </el-col>
            </el-col>

            <el-dialog title="邀请学生" :visible.sync="appletDialogVisible" width="30%">
                <div style="height: 300px;">
                    <div style="width: 100%;margin-bottom: 20px;">
                        <el-image style="width: 200px;height: 200px;" :src="'data:image/png;base64,' + codeUrl">
                            <div slot="error" class="image-slot">
                                <i class="el-icon-loading" style="font-size: 36px;margin-top: 50px;"></i>
                            </div>
                        </el-image>
                    </div>
                    <span class="mt10" style="font-size: 15px;color: rgb(109 149 221);">请打开微信扫一扫<br></span>
                    <span class="mt10" style="font-size: 15px;color: rgb(109 149 221);">使用劳动教育云小程序邀请学生加入~</span>
                </div>
            </el-dialog>
            <el-dialog title="添加" :visible.sync="dialogVisible" width="30%" :before-close="handleClose"
                @close="handleClose">
                <el-form ref="addform" :rules="rules" :model="addForm" label-width="80px">
                    <el-form-item label="姓名" prop="xm">
                        <el-input v-model="addForm.xm" placeholder="请输入学生姓名"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                        <el-input v-model="addForm.mobile" maxlength="11" placeholder="请输入手机号"></el-input>
                    </el-form-item>
                    <el-form-item label="学号" prop="xh">
                        <el-input v-model="addForm.xh" placeholder="请输入学号"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="证件号" prop="zjh">
                        <el-input v-model="addForm.zjh" maxlength="18" placeholder="请输入证件号"></el-input>
                    </el-form-item> -->
                    <el-form-item label="专业代码" prop="zydm">
                        <el-select v-model="addForm.zydm" filterable placeholder="请选择专业代码" @change="getClassData()">
                            <el-option v-for="item in zyList" :key="item.zydm" :label="item.zymc" :value="item.zydm">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="班级代码" prop="bjdm">
                        <el-select v-model="addForm.bjdm" filterable placeholder="请选择班级代码">
                            <el-option v-for="item in classList" :key="item.bjdm" :label="item.bjmc" :value="item.bjdm">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addStu">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 导入 -->
            <el-dialog title="导入" :visible.sync="exportShow" width="600px">
                <el-form ref="model" :rules="ruless" :model="model" label-width="80px">
                    <el-form-item label="专业代码" prop="zydm">
                        <el-select v-model="model.zydm" filterable placeholder="请选择专业代码" @change="getNewClassData()">
                            <el-option v-for="item in newZy" :key="item.zydm" :label="item.zymc" :value="item.zydm">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="学级" prop="xj">
                        <el-select v-model="model.xj" filterable placeholder="请选择学级代码" @change="changeClass2">
                            <el-option v-for="item in newClassList" :key="item.xj" :label="item.xj" :value="item.xj">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="班级代码" prop="bjdm">
                        <el-select v-model="model.bjdm" filterable placeholder="请选择班级代码" @change="changeClass">
                            <!-- <el-input value="item.bjdm" /> -->
                            <el-option v-for="item in newBxList" :key="item.bjdm" :label="item.bjmc" :value="item.bjdm">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="导入模板" prop="mb" v-if="model.zydm != '' && model.bjdm != ''">
                        <el-upload class="upload-demo" ref="upload" accept=".xlsx,.xls" :action="stuuploadfileurl"
                            :data="upData" :show-file-list="false" :on-success="success" :before-upload="beforeUpload">
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </el-dialog>
            <el-dialog title="编辑" width="350px" :visible.sync="show">
                <el-form :model="form">
                    <el-form-item label="姓名">
                        <el-input v-model="form.name" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="show = false">取 消</el-button>
                    <el-button type="primary" @click="save">确 定</el-button>
                </div>
            </el-dialog>
        </el-col>
    </el-row>
</template>

<script>
import minxins from "@/utils/exportStudent";
import {
    v4 as uuidv4
} from 'uuid';
export default {
    mixins: [minxins],
    data() {
        var checkPhone = (rule, value, callback) => {
            let pattern = /^1[3,4,5,6,7,8,9][0-9]{9}$/;
            console.log(pattern.test(value));
            if (value === '') {
                callback(new Error('请输入手机号'));
            } else if (!pattern.test(value)) {
                callback(new Error('请输入正确手机号'));
            } else {
                callback();
            }
        };
        return {
            maxrole: this.$store.state.maxRole,
            loading: false,
            stumburl: 'https://www.wytldy.com/file/1-sys-img/1687533660368导入-学生信息模板.xls',
            loginInfo: this.$store.state.loginInfo,
            upData: {
                schoolid: this.$store.state.schoolId,
                zydm: '',
                bjdm: ''
            },
            stuuploadfileurl: this.$url.baseURL + "/dstudent/impExcelStu",
            stupage: {
                total: 0,
                pageSize: 10,
                pageNum: 1,
                list: []
            },
            rules: {
                xm: [{
                    required: true,
                    message: '请输入学生姓名',
                    trigger: 'blur'
                }],
                mobile: [{
                    validator: checkPhone,
                    trigger: ['change', 'blur']
                },
                {
                    required: true,
                    message: '请输入手机号',
                    trigger: 'change'
                }],
                zydm: [{
                    required: true,
                    message: '请选择专业代码',
                    trigger: 'change'
                }],
                bjdm: [{
                    required: true,
                    message: '请选择班级代码',
                    trigger: 'change'
                }],
                xh: [{
                    required: true,
                    message: '请输入学号',
                    trigger: 'blur'
                }],
                // zjh: [{
                //     required: true,
                //     message: '请输入证件号',
                //     trigger: 'blur'
                // }]
            },
            form: {
                name: '',
                mobile: '',
                schoolid: this.$store.state.schoolId
            },
            addForm: {
                mobile: '',
                schoolId: this.$store.state.schoolId,
                bjdm: '',
                zydm: '',
                zjh: '',
                xm: '',
                xh: ''
            },
            zyList: [],
            classList: [],
            searchtext: '',
            schoolid: this.$store.state.schoolId,
            appletDialogVisible: false,
            codeUrl: '',
            user: this.$store.state.user,
            dialogVisible: false,
            UserId: null,
            show: false,
            newBxList: []
        };
    },
    created() {
        this.listSchoolStu();
        // console.log(this.maxRole,'-----------------')
    },
    methods: {
        handleEdit(item) {
            console.log(item);
            this.show = true;
            this.UserId = item.id
            this.form.name = item.name
        },
        // 删除
        handleDelete(item) {
            console.log(item, item.id, '删除id')
            let params = {
                id: item.id
            };
            console.log(params);
            this.$confirm('确定将' + item.name + '删除吗？确定之后用户将并不能登录。', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$api.Admin.delStudent(params).then(res => {
                    if (res.code == '0') {
                        this.$message.success('删除成功！');
                        this.listSchoolStu();
                    }
                })
            }).catch(() => { });
            // let params = {
            //     classid: item.id
            // };
            // this.$confirm('删除班级同时，班级下所有学生会一起删除，确定删除么？', '提示', {
            //     confirmButtonText: '确定',
            //     cancelButtonText: '取消',
            //     type: 'warning'
            // }).then(() => {
            //     this.$api.Admin.delClass(params).then(res => {
            //         if (res.code == '0') {
            //             this.listClass();
            //             this.$message.success('移除成功！');
            //         }
            //     })
            // }).catch(() => {
            // });
        },
        save() {
            let url = "/sysuser/modify"
            let params = {
                name: this.form.name,
                id: this.UserId
            }
            this.$ajax.post(url, params).then(res => {
                if (res.code == '0') {
                    this.$message.success('保存成功！');
                    this.listSchoolStu();
                    this.show = false
                }

            })
        },
        handleExport() {
            this.exportShow = true
            this.getZyListNew()
        },
        handleAdd() {
            this.dialogVisible = true
            this.getZyData()
        },
        invitstu() {
            this.appletDialogVisible = true;
            this.creatQrCode();
        },
        creatQrCode() {
            let token = this.$md5(uuidv4() + new Date().toLocaleString());
            this.$ajax.post('/comm/getInviteErWeiCode', {
                scene: encodeURIComponent(token),
                schoolid: encodeURIComponent(this.schoolid),
                uid: encodeURIComponent(this.user.id),
                type: 'stu'
            }).then(rs => {
                this.codeUrl = rs.url;
            })
        },
        addStu() {
            this.$refs['addform'].validate((valid) => {
                if (valid) {
                    this.$ajax.post('/dstudent/insertStudent', this.addForm).then(res => {
                        console.log(res);
                        if (res.state.code == 0) {
                            this.listSchoolStu();
                            this.dialogVisible = false;
                            this.$message.success('添加成功！');
                        } else {
                            this.$message.error(res.body.data);
                        }
                    })
                } else {
                    return false;
                }
            });
        },
        getZyData() {
            this.$ajax.post('/dzy/pagelist', {
                schoolid: this.schoolid,
                pageSize: 1000
            }).then(res => {
                console.log(res);
                if (res.code == 0) {
                    this.zyList = res.list.list
                    if (res.list.length != 0) {
                        this.addForm.zydm = res.list.list[0].zydm
                        this.getClassData()
                    }
                }
                // if (res.result == 'mobileExist') {
                //     this.$message.error('该手机号已存在！');
                // } else {
                //     this.$message.success('添加成功！');
                //     this.listSchoolTr();
                //     this.dialogVisible = false;
                // }
            })
        },
        getClassData() {
            this.$ajax.post('/dclass/classList', {
                schoolid: this.schoolid,
                zydm: this.addForm.zydm
            }).then(res => {
                console.log(res);
                if (res.code == 0) {
                    this.classList = res.list
                    if (res.list.length != 0) {
                        this.addForm.bjdm = res.list[0].bjdm
                    }
                }
            })

        },
        handleClose() {
            this.dialogVisible = false
            this.$refs['addform'].resetFields()
        },
        listSchoolStu(pageNum) {
            this.loading = true;
            let params = {
                schoolid: this.schoolid,
                pageNum: pageNum,
                searchtext: this.searchtext
            };
            this.$api.Admin.pageAllStu(params).then(res => {
                this.loading = false
                if (res.code == '0') {
                    console.log(res.list);
                    this.stupage = res.list;
                }

            })
        },
        handleDeleteStu(item) {
            console.log(item, '删除学生===')
            let params = {
                schoolid: this.schoolid,
                xh: item.xh
            };
            console.log(params);
            this.$confirm('确定将' + item.name + '删除吗？确定之后用户将并不能登录。', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$api.Admin.delStudent(params).then(res => {
                    if (res.code == '0') {
                        this.$message.success('删除成功！');
                        this.listSchoolStu();
                    }
                })
            }).catch(() => { });
        },
        beforeUpload(file) {
            console.log(file);
            const fileName = file.name;
            const index = fileName.lastIndexOf(".");
            const ext = fileName.substr(index + 1);
            const arr = ["xls", "xlsx"];
            const isOk = arr.includes(ext);
            if (!isOk) {
                this.$message.warning('导入模板应为xls/xlsx格式！');
                return false;
            }
        },
        success(res) {
            if (res.code == 10002) {
                this.$message.error(res.msg)
            } else {
                if (res.errinfo == "") {
                    this.listSchoolStu();
                    this.$message.success("导入成功")
                    this.exportShow = false
                } else {
                    this.$message.error(res.errinfo)
                    this.listSchoolStu();
                    this.exportShow = false
                }
            }

        }
    }
}
</script>

<style scoped lang="scss">
.main {
    position: relative;
    height: 100%;
}

.posa {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 100%;
    overflow-y: auto;
    background-color: #fff;

    h3 {
        font-size: 18px;
    }

    .label {
        display: block;
        width: 76px;
        height: 40px;
        line-height: 40px;
        font-weight: 600;
        font-size: 15px;
        margin-right: 10px;
    }

    .btn {
        // width: 120px;
        // height: 36px;
        // line-height: 36px;
        // background: #F3F4FB;
        // border: 1px solid #626BF1;
        // color: #626BF1;
        // border-radius: 10px;
        // cursor: pointer;
        // font-size: 16px;
        display: flex;
    }
}

.tab {
    // padding: 0 85px;
}

.height {
    height: 100%;
}

.el-table .warning-row {
    background: oldlace;
}

.el-table .success-row {
    background: #f0f9eb;
}

.delete-btn {
    display: block;
    padding: 3px 5px;
    width: 64px;
    height: 24px;
    line-height: 24px;
    background: linear-gradient(-13deg, #F97762, #F89F9F);
    border-radius: 12px;
    color: #fff;
}
</style>
